// lib/views/trade_history_page.dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/buy_record_controller.dart';
import '../../../data/models/stock_position_model.dart';
import '../../../data/datasource/local/database.dart';

class TradeHistoryPage extends StatelessWidget {
  final StockPositionModel position;

  const TradeHistoryPage({Key? key, required this.position}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final BuyRecordController controller = Get.find();
    final AppDatabase _database = Get.find();

    final history = _database.getTradeHistory(position.symbol);

    return Dialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '${position.name} (${position.symbol}) 交易历史',
              style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),
            FutureBuilder<List<Map<String, dynamic>>>(
              future: history,
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return const Center(child: CircularProgressIndicator());
                }

                if (snapshot.hasError || !snapshot.hasData || snapshot.data!.isEmpty) {
                  return const Center(child: Text('暂无交易历史'));
                }

                return SizedBox(
                  height: 300,
                  child: ListView.builder(
                    itemCount: snapshot.data!.length,
                    itemBuilder: (context, index) {
                      final record = snapshot.data![index];
                      final isBuy = record['type'] == 'buy';
                      final color = isBuy ? Colors.red : Colors.green;
                      final icon = isBuy ? Icons.arrow_downward : Icons.arrow_upward;

                      return ListTile(
                        leading: Icon(icon, color: color),
                        title: Text(
                          isBuy ? '买入' : '卖出',
                          style: TextStyle(fontWeight: FontWeight.bold, color: color),
                        ),
                        subtitle: Text(
                          '${record['price'].toStringAsFixed(2)} × ${record['quantity']}股',
                        ),
                        trailing: Text(
                          _formatDate(record['date']),
                          style: const TextStyle(fontSize: 12),
                        ),
                      );
                    },
                  ),
                );
              },
            ),
            const SizedBox(height: 16),
            Align(
              alignment: Alignment.centerRight,
              child: TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: const Text('关闭'),
              ),
            ),
          ],
        ),
      ),
    );
  }

  String _formatDate(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
  }
}